import java.io.File;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class DOM4JTest {

	public static void main(String[] args) {
		try {
			// 创建SAXReader的对象reader
			SAXReader reader = new SAXReader();
			// 通过reader对象的read方法加载books.xml文件,获取docuemnt对象。
			Document document = reader.read(
					new File("C:\\Users\\Administrator\\Desktop\\xmlchat\\xml-chat\\src\\test\\resources\\1.xml"));
			// 通过document对象获取根节点bookstore
			Element element = document.getRootElement();
			// 通过element对象的elementIterator方法获取迭代器
			Iterator<Element> iter = element.elementIterator();
			int index = 0;
			// 遍历迭代器，获取根节点中的信息（书籍）
			while (iter.hasNext()) {
				Element e = iter.next();
				System.out.println("第" + (index + 1) + "本书");
				List<Attribute> bookAttrs = e.attributes();
				for (Attribute attr : bookAttrs) {
					System.out.println("属性名：" + attr.getName() + "，属性值：" + attr.getValue());
				}
				index = index + 1;
				Iterator<Element> siter = e.elementIterator();
				while (siter.hasNext()) {
					e = siter.next();
					System.out.println(e.getName() + "=" + e.getStringValue());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
